// 用户注册
async function apiRegister(username, password) {
    return await fetch('/api/auth/register', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({username, password})
    });
}

// 获取所有商品
async function apiGetProducts() {
    const resp = await fetch('/api/products');
    if (!resp.ok) return [];
    return await resp.json();
}

// 获取单个商品
async function apiGetProduct(id) {
    const resp = await fetch('/api/products/' + id);
    if (!resp.ok) return null;
    return await resp.json();
}

// 发布商品
async function apiPublishProduct(data, image) {
    const formData = new FormData();
    formData.append('title', data.title);
    formData.append('price', data.price);
    formData.append('description', data.description);
    if (image) formData.append('image', image);
    return await fetch('/api/products', {
        method: 'POST',
        body: formData
    });
}

// 获取当前用户发布的商品
async function apiGetMyProducts() {
    const resp = await fetch('/api/users/me/products');
    if (!resp.ok) return [];
    return await resp.json();
}

// 删除商品
async function apiDeleteProduct(id) {
    return await fetch('/api/products/' + id, {method: 'DELETE'});
}
